<!-- 登录(普通版) -->

<template>
  <div id="Login">
    <el-form ref="form" class="CoreWeb-WebForm" :model="one">
      <!-- 标题 -->
      <div id="Login-title">{{ title }}</div>

      <!-- 账号 -->
      <el-form-item prop="account" :rules="{ required: true, message: '请输入账号' }" required>
        <el-input
          v-model.trim="one.account"
          :maxlength="20"
          placeholder="请输入账号"
          clearable
          @keyup.enter.native="toLogin"
        />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password" :rules="{ required: true, message: '请输入密码' }" required>
        <el-input
          v-model.trim="one.password"
          :maxlength="20"
          placeholder="请输入密码"
          show-password
          clearable
          @keyup.enter.native="toLogin"
        />
      </el-form-item>

      <!-- 按钮 -->
      <el-button type="primary" @click="toLogin">登录</el-button>
    </el-form>

    <!-- 方块气泡 -->
    <div v-for="item in 10" :key="item" class="Login-square" />
  </div>
</template>

<script>
// ============================== 导入依赖 ============================== //

import Vuex, { mapState, mapMutations, mapActions } from 'vuex'
import store from './store'

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'Login2',

  /**
   * 中心仓库
   */
  store: new Vuex.Store(store),

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    ...mapState(['INIT_ONE', 'one', 'refForm', 'needOne', 'readyOne']),

    /**
     * 标题
     */
    title: () => process.env.VUE_APP_TITLE,
  },

  /**
   * 监听属性 (深度 deep 首次 immediate)
   */
  watch: {
    /**
     * 监听单项开关
     */
    needOne(need) {
      need && this.remoteOne().then(this.completeOne).catch(this.stopOne)
    },

    /**
     * 监听单项就绪
     */
    readyOne() {
      location.reload()
    },
  },

  /**
   * 创建完成 (先抽取再调用)
   */
  created() {
    // 重置单项
    this.setOne()
  },

  /**
   * 挂载完成 (先抽取再调用)
   */
  mounted() {
    // 设置表单
    const refForm = this.$refs.form
    refForm.check = this.toSubmit
    this.setRefForm(refForm)
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    ...mapMutations(['setOne', 'setRefForm', 'startOne', 'completeOne', 'stopOne']),
    ...mapActions(['remoteOne']),

    /**
     * 点击登录
     */
    async toLogin() {
      await this.refForm.check()
      this.startOne()
    },

    /**
     * 提交表单 (重复提交时，可以闪烁提示)
     */
    async toSubmit() {
      const { $refs, $nextTick } = this

      $refs.form.clearValidate()
      await $nextTick()

      return new Promise((resolve) => {
        $refs.form.validate((valid) => valid && resolve())
      })
    },
  },
}
</script>

<style lang="scss">
@import '../Login/index.scss';
</style>
